/* **************************************************************************/
/*COPYRIGHT CCWIN-IN ALL RIGHTS RESERVED. THIS IS AN UNPUBLISHED WORK.      */
/*V8:ConvertMode=Report                                                     */
/*V8:WebEnabled=Yes                                                         */
/*V8:RunMode=Character,Windows                                              */
/*EXTRACTING DATA FROM MFG/PRO                                              */
/****************************************************************************/
/* PROCEDURE NAME        : xxcinvreverseapi.p                               */
/* PROCEDURE TYPE        : CINVOICE REVERSE API                             */
/* DESCRIPTION           : Po export Process                                */
/*                                                                          */     
/* INCLUDE FILES         :                                                  */
/* CALLED BY             :                                                  */
/* CALLED PROCEDURES     :                                                  */
/****************************************************************************/
/* CREATED BY            : Gaoyan                                29-Jul-24  */
/****************************************************************************/ 
/****************************************************************************/
/****************************************************************************/

{us/mf/mfdtitle.i}
{us/bbi/gplabel.i}
{us/wb/wbrp01.i}
{xxjson.i}
{xxcimload.i}


{xxapilog.i}

&SCOPED-DEFINE TimeStamp1 substring(string(year(today), "9999"),3) + string(month(today), "99") + string(day(today), "99")
&SCOPED-DEFINE TimeStamp2 substring(string(time, "HH:MM:SS"), 1, 2) + substring(string(time, "HH:MM:SS"), 4, 2) + substring(string(time, "HH:MM:SS"), 7, 2)

define input parameter vc_inputjson             as character format "x(60)" no-undo.
define input parameter vc_outputjson            as character format "x(60)" no-undo.
define input parameter vc_import                as logical  no-undo.


define variable vi_filecount          as integer                  no-undo.
define variable vi_reccount           as integer                  no-undo.
define variable vi_errorcount         as integer                  no-undo.
define variable vc_filename           as character                no-undo.
define variable vc_topath             as character                no-undo.
define variable v_runproagram         as character                no-undo.
define variable vc_traceid            as character                no-undo.
define variable vi_newid              as int64                    no-undo.
define variable v_errorstatus         as logical                    no-undo.


 define temp-table ttSearchCondition no-undo
        field reversepostingyear           as   integer
        field reversepostingperiod         as   integer
        field reversepostingdate           as   date
        field reverseinvoiceType           as   character
        field reverseInvoiceJournal        as   character
        field AdjustmentJournal            as   character
        field reversecompancode            as   character
        field reverseinvoiceref            as   character
        field tcCInvoiceRemark             as   character
        field tt_userid                    as   character
        field traceid                      as   character
        .
        
        
 define buffer b_journal for journal.       
        

 DEFINE DATASET dsSearchCondition FOR ttSearchCondition.

   hdataset = dataset dsSearchCondition:HANDLE.   

{proxy/bcinvoice/apireversecinvoicedef.i}



  output to /home/mfg/invreverse.log.
  put "run invreverse" skip.
mainloop:
repeat on error undo mainloop, leave mainloop:
  
 
   /* Output and Batch Input */
   
   {us/xx/xxworkpath_e.i &outbound=YES &inbound=no &archive=YES}

assign m_outpath     = m_outpath + "sinv/"
       m_archpath    = m_archpath + "sinv/"
       m_successpath = m_successpath + "sinv/"
       m_errorpath   = m_errorpath + "sinv/"
       m_workpath    = m_workpath + "sinv/".


   
   
   /* Load SEARCH conditions from JSON  */ 
   
   vc_outputjson = replace(vc_inputjson,".json",".run.out.json").  
   
   run loadjsonfile(input vc_inputjson,
                    input vc_outputjson,
                    output vl_RetOK).
                    
  if vl_RetOK then do:
   
   empty temp-table tFcMessages.
   vi_newid = 0.
   
   for each ttSearchCondition .
   export ttSearchCondition.
   if  ttSearchCondition.reverseInvoiceJournal = ""    then ttSearchCondition.reverseInvoiceJournal =  "APINVCOR".
   if  ttSearchCondition.AdjustmentJournal = "" then ttSearchCondition.AdjustmentJournal = "APADJ".
   if  ttSearchCondition.reverseinvoiceType = "" then ttSearchCondition.reverseinvoiceType = "INVOICECORRECTION".
   
   find journal where journal.journalcode = entry(2,ttSearchCondition.reverseinvoiceref,"/") no-lock no-error.
   find b_journal where b_journal.journalcode = ttSearchCondition.reverseInvoiceJournal no-lock no-error.
   find company where company.companycode = ttSearchCondition.reversecompancode no-lock no-error.
   
   find last cinvoice no-lock where cinvoice.journal_id = b_journal.journal_id 
                                and cinvoice.company_id = company.company_id
                                and cinvoice.CInvoicePostingYear = ttSearchCondition.reversepostingyear
                                no-error.
     if available cinvoice then vi_newid = cinvoice.cinvoicevoucher + 1.
     else vi_newid = 1.
   
    for each cinvoice no-lock where cinvoice.cinvoicevoucher = int64(entry(3,ttSearchCondition.reverseinvoiceref,"/"))
                                and cinvoice.company_id = company.company_id
                                and cinvoice.CInvoicePostingYear =  ttSearchCondition.reversepostingyear .

    
    assign     icReverseInvoiceType   = ttSearchCondition.reverseinvoiceType
               iiReversePostingYear = ttSearchCondition.reversepostingyear
               iiReversePostingPeriod = ttSearchCondition.reversepostingperiod
               itReversePostingDate = ttSearchCondition.reversepostingdate
               icReverseInvoiceJournal = ttSearchCondition.reverseInvoiceJournal
               iiReverseInvoiceVoucher = vi_newid
               icAdjustmentJournal = ttSearchCondition.AdjustmentJournal
               iiReversedCInvoiceRegistrationNr = Cinvoice.CInvoiceRegistrationNr
               vcProxyCompanyCode = ttSearchCondition.reversecompancode
               igReversedCompanyId = company.company_id
    
                  .
    
    
    {proxy/bcinvoice/apireversecinvoicerun.i}
    
   end.  /*   for each ttSearchCondition . */
   
   for each tFCMessages.
   export tFcMessages.
   end.
    
    if oiReturnStatus >= 0 then 
    do:
    v_errorstatus = no.
    
     find usr where usr.UsrLogin =   ttSearchCondition.tt_userid no-lock no-error.
                                          
                      
                      
                      
                     for first Cinvoice
                     where string(CInvoice_ID) = string(oiReverseCInvoiceId)
                     exclusive-lock: 
                     
                     if ttSearchCondition.tt_userid  <> "" and available usr 
                     then cinvoice.LastModifiedUser =  ttSearchCondition.tt_userid .
                     
                     assign                    
                     Cinvoice.CInvoiceDescription    = ttSearchCondition.tcCInvoiceRemark. 

                     end. /*for first Cinvoice*/
                     find journal of Cinvoice no-lock no-error.
                     for first cinvoiceposting where string(cinvoiceposting.cinvoice_id) = string(oiReverseCInvoiceId):
                     find first posting where posting.posting_id = cinvoiceposting.posting_id no-error.
                     if avail posting then
                     do:
                     assign  postingtext = Cinvoice.cinvoicedescription .
                     
                     if avail usr then 
                     assign posting.CreatorUsr_ID = usr.usr_id.
                     
                     
                     end.
                     vi_errorcount = vi_errorcount + 1.
                     create api_status.
                      assign api_status.data_seq     = vi_errorcount
                             api_status.return_status  = "SUCCESS"
                             api_status.message_type = Cinvoice.CInvoiceReference
                             api_status.message_string  = string(CInvoicePostingYear) + "/" + 
                                                          journal.journalcode + "/" + 
                                                          string(Cinvoice.cinvoicevoucher,"999999999") 
                                                        
                             api_status.dataid  = ttSearchCondition.reverseinvoiceref  
                             api_status.billnbr  = ttSearchCondition.reverseinvoiceref                                       
                             api_status.traceid = ttSearchCondition.traceid. 
                     
    end.                  
       end. /* oiReturnStatus */   
    else v_errorstatus = yes.
       
    for each tFcMessages.
      if tFCMessages.tcFcType = "W" then next.  

                     if index(tFcMessages.tcFcMessage,"warning") <> 0 or
                     index(tFcMessages.tcFcMessage, "The sum of the base and tax amounts") <> 0 then
                     next.
                     
                     if index(tFcMessages.tcFcMsgNumber, "qadfin-500498") <> 0 then
                     next.
                     
                     if index(tFcMessages.tcFcMsgNumber, "QadFin-8125") <> 0 then
                     next.
                                         
                    
                     
                     if tFcMessages.tcFcFieldName <> "" then
                     do:
                     vi_errorcount = vi_errorcount + 1.
                      create api_status.
                      assign api_status.data_seq     = vi_errorcount
                             api_status.return_status  = "FAILED"
                             api_status.message_type = "API_ERROR"
                             api_status.message_string  = gettermlabel("SEVERITY",8) + " = " +
                                                          string(tFcMessages.tiFcSeverity) + " | " +
                                                          tFcMessages.tcFcMessage + " | " +
                                                          gettermlabel("FIELD_NAME",10) + " = " +
                                                          tFcMessages.tcFcFieldName + " | " +
                                                          gettermlabel("FIELD_LABEL",11) + " = " +
                                                          tFcMessages.tcFcFieldLabel + " | " +
                                                          gettermlabel("FIELD_VALUE",11) + " = " +
                                                          tFcMessages.tcFcFieldValue + " | " +
                                                          tFcMessages.tcFcMsgNumber
                             api_status.dataid  = ttSearchCondition.reverseinvoiceref  
                             api_status.billnbr  = ttSearchCondition.reverseinvoiceref                                       
                             api_status.traceid = ttSearchCondition.traceid . 
                     end.
                    
                     else
                     do:
                     vi_errorcount = vi_errorcount + 1.
                      create api_status.
                      assign api_status.data_seq     = vi_errorcount
                             api_status.return_status  = "FAILED"
                             api_status.message_type = "API_ERROR"
                             api_status.message_string  = gettermlabel("SEVERITY",8) + " = " +
                                                          string(tFcMessages.tiFcSeverity) + " | " +
                                                          tFcMessages.tcFcMessage + " | " +
                                                          tFcMessages.tcFcMsgNumber
                             api_status.dataid  = ttSearchCondition.reverseinvoiceref  
                             api_status.billnbr  = ttSearchCondition.reverseinvoiceref                                       
                             api_status.traceid = ttSearchCondition.traceid . 
                     end. /* else do */
                     
    
    end. /* for each tFcMessages. */

 


end. /*  for each ttSearchCondition . */

end. /*   if vl_RetOK then do: */

 /* Create output json */                   
         run writejsonfile(input hresult,
                  input vc_outputjson,
                  input "FILE",
                  input True,
                  input "UTF-8",
                  output vl_RetOK,
                  output vc_errorstring).
                  
      for each ttSearchCondition.

       vi_reccount = vi_reccount + 1.
              
       run CreateAPILogMaster(input vc_traceid,
                              input "supplierinoicereverse",
                              input "xxcinvreverseapi.p",
                              input "",
                              input "",
                              input vc_inputjson,
                              input ttSearchCondition.reverseinvoiceref,
                              input "",
                              input "xxapicinvrevdata_det",
                              input vi_reccount).  

      end.  /*  for each ttSearchCondition.*/    
                  
                  
       do vi_filecount = 1 to 5:
          /* when success move cim log file to archive directory  */
          /* when failed move cim log file to error directory  */   
          /*  move status json file to out directory for API return */   
          /* when success move previous step .p and json file to archive directory  */
          /* when failed move previous step .p and json file to error directory  */       
          case vi_filecount:
      
          when 1 then
          assign vc_filename = replace(vc_inputjson,".json",".p")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 2 then
          assign vc_filename = vc_inputjson
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 3 then
          assign vc_filename = replace(vc_inputjson,".json",".dat")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 4 then
          assign vc_filename = replace(vc_inputjson,".json",".run.log")
                 vc_topath   = m_outpath.
          when 5 then
          assign vc_filename = replace(vc_inputjson,".json",".run.out.json")
                 vc_topath   =  m_outpath.
          end case.
          
         if vl_RetOK then 
         put unformatted vc_filename " " skip
         vc_topath " " skip 
         vi_filecount skip.
     
        
          
          run cimfilehandle(input vc_filename,
                            input vc_topath,
                            input no ).                 
                   
          
     
       end.       /* do vi_filecount = 1 to 5: */        
      
   
   
   leave.
   
   end. /* repeat */
